package cn.com.utt.common.zk;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class APIDiscovery {
	// private static final Logger LOGGER =
	// LoggerFactory.getLogger(ServiceDiscovery.class);
	@Value("${zookeeper.api}")
	private String ZK_REGISTRY_PATH = "/api/node00";
	private CountDownLatch latch = new CountDownLatch(1);

	private volatile List<String> dataList = new ArrayList<>();

	private String registryAddress;

	public APIDiscovery(@Value("${zookeeper.addr}") final String registryAddress) {
		this.registryAddress = registryAddress;
		ZooKeeper zk = connectServer();
		if (zk != null) {
			watchNode(zk);
		}
	}

	public String discover() {
		String data = null;
		int size = dataList.size();
		if (size > 0) {
			if (size == 1) {
				data = dataList.get(0);
				System.out.println();
				System.out.println("using only data: {}" + data);
			} else {
				data = dataList.get(ThreadLocalRandom.current().nextInt(size));
				System.out.println("using random data: {}" + data);
			}
		}
		return data;
	}

	private ZooKeeper connectServer() {
		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(registryAddress, 60, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					if (event.getState() == Event.KeeperState.SyncConnected) {
						latch.countDown();
					}
				}
			});
			latch.await();
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
		return zk;
	}

	private void watchNode(final ZooKeeper zk) {
		try {
			List<String> nodeList = zk.getChildren(ZK_REGISTRY_PATH, new Watcher() {
				@Override
				public void process(WatchedEvent event) {
					if (event.getType() == Event.EventType.NodeChildrenChanged) {
						watchNode(zk);
					}
				}
			});
			List<String> dataList = new ArrayList<>();
			for (String node : nodeList) {
				byte[] bytes = zk.getData(ZK_REGISTRY_PATH + "/" + node, false, null);
				dataList.add(new String(bytes));
			}
			System.out.println("api node data: {}" + dataList);
			this.dataList = dataList;
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
}
